﻿namespace BadHabit.WPFTools
{
    using System;
    using System.Windows;
    using System.Windows.Input;

    /// <summary>
    /// Thanks to Mike.
    /// http://mikescodeblog.blogspot.com/2007/12/drag-and-drop-in-wpf.html
    /// </summary>
    public class DragDropHandler
    {
        private FrameworkElement dragElement = null;
        private bool dragging = false;

        private Point dragStart;
        private DataObject dataObject = null;

        public DragDropHandler(FrameworkElement dragElement, DataObject dataObject)
        {
            this.dragElement = dragElement;
            this.dataObject = dataObject;

            this.dragElement.PreviewMouseDown += new MouseButtonEventHandler(this.DragElementMouseLeftButtonDown);
            this.dragElement.MouseMove += new MouseEventHandler(this.DragElementMouseMove);
            this.dragElement.PreviewMouseUp += new MouseButtonEventHandler(this.DragElementPreviewMouseUp);
        }

        private void DragElementPreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            this.dragging = false;
            this.dragElement.ReleaseMouseCapture();
        }

        private void DragElementMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.Source is ComboBox)
            {
                return;
            }

            if (!this.dragging)
            {
                this.dragging = true;
                this.dragStart = e.GetPosition(this.dragElement);
            }
        }

        private bool indrag = false;

        private void DragElementMouseMove(object sender, MouseEventArgs e)
        {
            if (this.dragging && e.LeftButton == MouseButtonState.Pressed && !this.indrag)
            {
                Point currentPos = e.GetPosition(this.dragElement);

                if ((Math.Abs(currentPos.X - this.dragStart.X) > 5) || (Math.Abs(currentPos.Y - this.dragStart.Y) > 5))
                {
                    this.dragElement.CaptureMouse();
                    this.indrag = true;

                    ////Console.WriteLine("start drag"); 
                    DragDropEffects de = DragDrop.DoDragDrop(this.dragElement, this.dataObject, DragDropEffects.Move);
                    ////Console.WriteLine("end drag");
                    this.indrag = false;
                    this.dragging = false;
                    this.dragElement.ReleaseMouseCapture();
                }
            }
        }
    }
}
